const router = require('koa-router')()
const db = require('../utils/mysql.js');
const config  = require('../../config')[process.env.NODE_ENV];
router.get('/loginOut', ctx=>{
  ctx.cookies.set('user','',{maxAge:0});
  ctx.body={'err':0}
});
router.get('/info',async ctx=>{
  // ctx.log('infolll')
  // var user = JSON.parse(ctx.cookies.get('user')||'{}');
  var user = JSON.parse(new Buffer(ctx.cookies.get('user'), 'base64').toString()||'{}');
  if(user && user.id){
    user = await queryUser({id:user.id});
    if(user.length){
      user = user[0];
    }
    else{
      user = {}
    }
  }
  else{
    user = {};
  }
  ctx.body=user;
});
router.get('/getlogininfo',async ctx=>{
  // ctx.log('infolll')
  // var user = JSON.parse(ctx.cookies.get('user')||'{}');
  let user = ctx.cookies.get('user');
  if(user){
    user = JSON.parse(new Buffer(ctx.cookies.get('user'), 'base64').toString()||'{}');
  }
  let offerNum =0;
  if(user && user.id){
    user = await queryUser({id:user.id})
    if(user.length){
      user = user[0]
      offerNum = await queryUserOffer(user.id)
      user.offerNum = offerNum
    }
    else{
      user = ''
    }
  }
  else{
    user = ''
  }

  ctx.body={'err':0,'user':user}
});
router.post('/addUser',async ctx=>{
	// 新增用户
  var data = ctx.request.body;
  var userName = data.userName;
  if(!userName){
    ctx.body={'err':1,'msg':'用户名为空'};
    return ;
  }
  if(!data.password){
    ctx.body={'err':1,'msg':'密码为空'};
    return ;
  }
  const result = await queryUser({userName:userName});
  if(result.length>0){
    ctx.body={'err':1,'msg':'用户名已存在'};
    return ;
  }
  var sql = "insert into blog_user(user_name,password,show_name) values (:userName,:password,:showName)";
  await db.query(sql,{userName:userName,password:data.password,showName:data.showName});
  // ctx.flash('success','注册成功');
  ctx.body={'err':0};
});
router.post('/pwdlogin', async ctx=>{
	// 密码登录
  var data = ctx.request.body;
  var account = data.account;
  if(!account){
     ctx.body={'err':1,'msg':'用户名为空'};
     return ;
  }
  if(!data.password){
     ctx.body={'err':1,'msg':'密码为空'};
     return ;
  }
  const result = await queryUser({account:account,pwd:data.password});
  if(result.length===0){
    ctx.body={'err':1,'msg':'用户名或密码错误'};
    return ;
  }
  // ctx.log(JSON.stringify(result[0]))
  ctx.cookies.set('user',  new Buffer(JSON.stringify(result[0])).toString('base64'));
  ctx.body={'err':0};
});

async function queryUser(user={},userLike={}){
  let sql = "select id, name,num,limit_amount limitAmount,id_card idCard,zone rem,house_num houseNum ,phone,pwd,login_by loginBy from bxc_user_"+config.tt+" where 1";
  const queryObj = {};
  for(let u in user){
    sql += " and "+u+"=:"+u;
    queryObj[u] = user[u];
  }
  for(let u in userLike){
    sql += " and "+u+" like %:"+u+"_like%";
    queryObj[u+'_like'] = userLike[u];
  }
  return await db.query(sql,queryObj);
}

async function queryUserOffer(userId){
	let sql = "select count(*) num from hrc_car_sold_"+config.tt+" where user_id = :userId";
	const res = await db.query(sql,{'userId':userId});
  return res[0].num;
}

router.get('/my/:username', ctx=>{
  ctx.send('user: ' + ctx.params.username);
});

router.get('/', ctx=>{
  var user = JSON.parse(ctx.cookies.get('user')||'{}');
	if(user && user.id){
  	ctx.send('user: ' + util.inspect(user.showName));
		return;
	}
  ctx.send('respond with a resource');
});

module.exports = router;
